﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper.Internal.Mappers;
using BW.WMS.BasicData_LC.Dto.Input;
using BW.WMS.BasicData_LC.Dto.OutPut;
using BW.WMS.CodeEnum;
using BW.WMS.Model;
using Microsoft.Extensions.Logging;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using Volo.Abp.Timing;
using Volo.Abp.Uow;

namespace BW.WMS.BasicData_LC
{
    /// <summary>
    /// 订单管理应用服务
    /// </summary>
    public class OrderFormAppService : ApplicationService, IOrderFormAppService
    {
        private readonly IRepository<OrderFormModel, Guid> _orderRepository;

        private readonly IRepository<Dm_Item, Guid> _itemRepository;

        private readonly IRepository<Dm_Ent, Guid> _entRepository;

        public OrderFormAppService(IRepository<OrderFormModel, Guid> orderRepository,
            IRepository<Dm_Item, Guid> itemRepository, 
            IRepository<Dm_Ent, Guid> entRepository)
        {
            _orderRepository = orderRepository;
            _itemRepository = itemRepository;
            _entRepository = entRepository;
        }
        /// <summary>
        /// 供应商添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> AddEnt(AddDm_EntInput input)
        {
            input.Id = Guid.NewGuid();
            var result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "创建成功";
            var book = ObjectMapper.Map<AddDm_EntInput, Dm_Ent>(input);
                
            var a = await _entRepository.InsertAsync(book);

            result.Data = 1;

            if (a == null)
            {
                result.Code = ApiEnum.Error;
                result.Message = "创建失败";
                result.Data = -1;
            }
            return result;
        }



        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<ApiResult<int>> AddOrderForm(OrderFormInput input)
        {
            try
            {
                input.Id=Guid.NewGuid();
                // 使用ABP的对象映射器
                var orderEntity = ObjectMapper.Map<OrderFormInput, OrderFormModel>(input);
                orderEntity.CreateTime = DateTime.Now; // 使用标准DateTime
                
                // 插入数据库
                var insertedOrder = await _orderRepository.InsertAsync(orderEntity, autoSave: true);

                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Message = "订单添加成功", // 暂时使用硬编码字符串
                    Data = 1
                };
            }
            catch (BusinessException ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Fail,
                    Message = ex.Message,
                    Data = 0
                };
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "添加订单失败"); // 修正日志调用
                return new ApiResult<int>
                {
                    Code = ApiEnum.Error,
                    Message = "添加订单失败",
                    Data = 0
                };
            }
        }
        /// <summary>
        /// 供应商下拉框
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<List<Dm_EntDto>>> GetEnt()
        {
            var departmentsQuery = await _entRepository.GetQueryableAsync();

            var departmentsList = departmentsQuery.ToList();


            var dtos = ObjectMapper.Map<List<Dm_Ent>, List<Dm_EntDto>>(departmentsList);

            return new ApiResult<List<Dm_EntDto>>
            {
                Code = ApiEnum.Success,
                Message = "获取供应商下拉框列表成功",
                Data = dtos
            };
        }
        /// <summary>
        /// 商品信息下拉框
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<List<Dm_ItemDto>>> GetItem()
        {
            var departmentsQuery = await _itemRepository.GetQueryableAsync();

            var departmentsList = departmentsQuery.ToList();


            var dtos = ObjectMapper.Map<List<Dm_Item>, List<Dm_ItemDto>>(departmentsList);

            return new ApiResult<List<Dm_ItemDto>>
            {
                Code = ApiEnum.Success,
                Message = "获取 商品信息下拉框列表成功",
                Data = dtos
            };
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<ApiResult<int>> GetOrderDel(Guid id)
        {
    
                var orderEntity = await _orderRepository.GetAsync(id);

                // 执行删除
                await _orderRepository.DeleteAsync(id);

                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Message = "订单删除成功",
                    Data = 1
                };
            
          
        }

        /// <summary>
        /// 分页查询订单
        /// </summary>
        /// <param name="output"></param>
        /// <returns></returns>
        public async Task<ApiPaging<OrderFormDto>> GetOrderForm(OrderFormOutput output)
        {
 
                // 获取查询对象
                var queryable = await _orderRepository.GetQueryableAsync();
                
                // 计算总数
                var totalCount = await AsyncExecuter.CountAsync(queryable);
                
                // 分页查询 - 使用标准的Skip和Take
                var orders = await AsyncExecuter.ToListAsync(
                    queryable
                        .OrderByDescending(x => x.CreationTime)
                        .Skip((output.pageindex - 1) * output.pagesize)
                        .Take(output.pagesize)
                );

                // 使用ABP对象映射器
                var orderDtos = ObjectMapper.Map<List<OrderFormModel>, List<OrderFormDto>>(orders);

                // 计算总页数
                var totalPages = (int)Math.Ceiling((double)totalCount / output.pagesize);

                return new ApiPaging<OrderFormDto>
                {
                    Code = ApiEnum.Success,
                    Message = "查询成功",
                    Data = default,
                    PageData = orderDtos,
                    TotalCount = totalCount,
                    TotalPages = totalPages
                };
            }

        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <returns></returns> 
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<List<OrderFormDto>>> GetOrderFormList()
        {
            var departmentsQuery = await _orderRepository.GetQueryableAsync();

            var departmentsList = departmentsQuery.ToList();


            var dtos = ObjectMapper.Map<List<OrderFormModel>, List<OrderFormDto>>(departmentsList);

            return new ApiResult<List<OrderFormDto>>
            {
                Code = ApiEnum.Success,
                Message = "获取 商品信息下拉框列表成功",
                Data = dtos
            };
        }



        /// <summary>
        /// 更新订单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<ApiResult<int>> UpdateOrderForm(OrderFormInput input)
        {
            var result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "修改订单成功";

            var data = await _orderRepository.GetAsync(x => x.OrderFormId == input.OrderFormId);

            data = ObjectMapper.Map(input,data);

            var a = await _orderRepository.UpdateAsync(data);

            result.Data = 1;

            if (a == null)
            {
                result.Code = ApiEnum.Error;
                result.Message = "修改失败";
                result.Data = -1;
            }
            return result;
        }
    }
}
